package com.allwees.core.common.util.http;

import com.allwees.core.common.constant.EPlatform;
import com.allwees.core.common.i18n.UTF8Control;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;

@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private final static String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        setTraceIdToMDC();
        buildRequestInfo(request);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(TRACE_ID);
        RequestContext.removeContext();
    }

    private void setTraceIdToMDC() {
        String traceId = java.util.UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        MDC.put(TRACE_ID, traceId);
    }

    private void buildRequestInfo(HttpServletRequest request) {
        RequestContext.RequestInfo info = new RequestContext.RequestInfo();
        EPlatform platform = EPlatform.parseFrom(request.getHeader(RequestUtil.X_PLATFORM));
        info.setPlatform(platform);
        info.setAgent(StringUtils.trimToNull(request.getHeader(RequestUtil.USER_AGENT)));
        info.setAppVersion(StringUtils.trimToNull(request.getHeader(RequestUtil.X_APPVERSION)));
        info.setPromChannel(StringUtils.trimToNull(request.getHeader(RequestUtil.X_PROMOTION_CHANNEL)));
        info.setChannel(StringUtils.trimToNull(request.getHeader(RequestUtil.X_CHANNEL)));
        info.setApiVersion(StringUtils.trimToNull(request.getHeader(RequestUtil.X_API_VERSION)));
        info.setLocale(request.getLocale());
        info.setResourceBundle(ResourceBundle.getBundle(
                "message", Optional.ofNullable(info.getLocale()).orElse(Locale.US), UTF8Control.instance()));
        info.setRemoteAddr(RequestUtil.getIpFromRequest(request));
        info.setPath(request.getRequestURI());
        RequestContext.setContext(info);
    }
}